﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.Exceptions.Database;
using System.Data.SqlClient;
using BSCMFF.Core.BusinessLayer;

namespace BSCMFF.Web.Pages.Surveys
{
    public partial class ManageSurveys : BSCMFF.Core.MultiLanguagePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RadGridSurveys_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "InitInsert")
            {
                Response.Redirect("CreateSurvey.aspx");
            }

            if (e.CommandName == "Preview")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);
                Response.Redirect("FillSurvey.aspx?Preview=yes&Survey_FormID=" + sfID);
            }

            if (e.CommandName == "Start")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                BSCEntities context = new BSCEntities();
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

                Survey_Form sf = (from sfs in context.Survey_Form
                                  where sfs.ID == sfID
                                  select sfs).SingleOrDefault();

                sf.Started = true;
                AssignRandomEmployees(sf.ID, (int)sf.NumberOfEmployees);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't start survey: " + ex.Message);
                }
                RadGridSurveys.Rebind();

            }
            if (e.CommandName == "Finish")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                BSCEntities context = new BSCEntities();
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

                Survey_Form sf = (from sfs in context.Survey_Form
                                  where sfs.ID == sfID
                                  select sfs).SingleOrDefault();

                sf.Started = true;
                sf.Finished = true;

                //SqlParameter sqlSFID = new SqlParameter();
                //sqlSFID.ParameterName = "@surveyID";
                //sqlSFID.Value = sfID;

                //object[] parms = new object[1];
                //parms[0] = sqlSFID;

                try
                {
                    context.SaveChanges();
                    context.FinishSurvey(sfID);
                    //context.ExecuteStoreCommand("FinishSurvey", parms);
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't finish survey: " + ex.Message);
                }
                RadGridSurveys.Rebind();
            }

            if (e.CommandName == "Delete")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                BSCEntities context = new BSCEntities();
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

                Survey_Form sf = (from sfs in context.Survey_Form
                                  where sfs.ID == sfID
                                  select sfs).SingleOrDefault();

                context.DeleteObject(sf);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't delete survey: " + ex.Message);
                }
                RadGridSurveys.Rebind();
            }
        }

        private void AssignRandomEmployees(int surveyID, int numberOfEmployees)
        {
            BSCEntities context = new BSCEntities();

            List<int> usersID = (from user in context.Users
                                 select user.ID).ToList();

            List<int> randomizedUsersIDs = ShuffleList<int>(usersID);

            for (int i = 0; i < numberOfEmployees; ++i)
            {
                Survey_User su = new Survey_User();
                su.Survey_Form_FK = surveyID;
                su.User_FK = randomizedUsersIDs[i];
                su.Filled = false;
                context.AddToSurvey_User(su);
            }

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't assign survey to employees: " + ex.Message);
            }
        }

        private List<E> ShuffleList<E>(List<E> inputList)
        {
            List<E> randomList = new List<E>();

            Random r = new Random();
            int randomIndex = 0;
            while (inputList.Count > 0)
            {
                randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list
                randomList.Add(inputList[randomIndex]); //add it to the new, random list
                inputList.RemoveAt(randomIndex); //remove to avoid duplicates
            }

            return randomList; //return the new random list
        }
    }
}